<style>
    .demo-spin-icon-load {
        animation: ani-demo-spin 1s linear infinite;
    }

    @keyframes ani-demo-spin {
        from {
            transform: rotate(0deg);
        }
        50% {
            transform: rotate(180deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
</style>
<template>
    <Row gutter="16">
        <Col span="10">
        <Card :bordered="false">
            <p slot="title">
                <Icon type="android-menu"></Icon>
                菜单列表
            </p>
            <a href="#" slot="extra">

                <Tooltip content="新增" placement="bottom-start">
                    <Button type="info" shape="circle" icon="plus-round" @click="create()"></Button>
                </Tooltip>

                <Tooltip content="删除" placement="bottom-start">
                    <Button type="error"  shape="circle" icon="minus-round" @click="del()"></Button>
                </Tooltip>

                <Tooltip content="编辑" placement="bottom-start">
                    <Button type="success"  shape="circle" icon="edit" @click="edit()"></Button>
                </Tooltip>

                <Tooltip content="刷新" placement="bottom-start">
                    <Button shape="circle" icon="refresh" @click="refresh()"></Button>
                </Tooltip>
            </a>

            <Tree ref="menuTree" :data="menusData" :load-data="loadData" @on-select-change="select"
                  @on-toggle-expand="expand"></Tree>
        </Card>
        </Col>

        <Col span="14">
        <Card :bordered="false">
            <p slot="title">
                <Icon type="android-clipboard"></Icon>
                菜单详情预览
            </p>
            <div>
                <Form :model="formItem" :label-width="80">
                    <Row>
                        <Col span="12">
                        <FormItem label="菜单名称">
                            <Input maxlength="50" readonly="true" v-model="formItem.menuName" placeholder=""></Input>
                        </FormItem>
                        </Col>

                        <Col span="12">
                        <FormItem label="路由地址">
                            <Input maxlength="50" readonly="true" v-model="formItem.menuUrl" placeholder=""></Input>
                        </FormItem>
                        </Col>

                        <Col span="12">
                        <FormItem label="权限值">
                            <Input maxlength="50" readonly="true" v-model="formItem.permission" placeholder=""></Input>
                        </FormItem>
                        </Col>

                        <Col span="12">
                        <FormItem label="图标">
                            <Input maxlength="50" readonly="true" v-model="formItem.icon" placeholder=""></Input>
                        </FormItem>
                        </Col>

                        <Col span="12">
                        <FormItem label="排序">
                            <Input type="number" readonly="true" v-model="formItem.sort" placeholder=""></Input>
                        </FormItem>
                        </Col>

                        <Col span="12">
                        <FormItem label="状态">
                            <i-switch v-model="formItem.menuStatus" disabled size="large" true-value="1" false-value="0">
                                <span slot="open">启用</span>
                                <span slot="close">禁用</span>
                            </i-switch>
                        </FormItem>
                        </Col>

                        <Col span="24">
                        <FormItem label="备注">
                            <Input maxlength="1000" readonly="true" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                                   v-model="formItem.remark"
                                   placeholder=""></Input>
                        </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </Card>

        <Card :bordered="false">
            <p slot="title">
                <Icon type="android-list"></Icon>
                资源列表
            </p>

            <a href="#" slot="extra">

                <Tooltip content="新增" placement="bottom-start">
                    <Button type="info" :disabled="roleOpDisabled" shape="circle" icon="plus-round" @click="createOp()"></Button>
                </Tooltip>

                <Tooltip content="刷新" placement="bottom-start">
                    <Button :disabled="roleOpDisabled" shape="circle" icon="refresh" @click="loadOp()"></Button>
                </Tooltip>
            </a>

            <Table highlight-row :loading="loading" stripe border :columns="columns" :data="rows"
                   @on-current-change="handleRowChange"></Table>

            <div style="margin: 10px;overflow: hidden">
                <div style="float: right;">
                    <Page :total="total" show-total="true" placement="top" show-sizer @on-change="goPage"></Page>
                </div>
            </div>
        </Card>

        <Spin fix size="large" fix v-if="spinShowPanel">
            <Icon type="load-c" size="18" class="demo-spin-icon-load"></Icon>
            <div>拼命加载中...</div>
        </Spin>

        </Col>


        <Modal v-model="roleModel" :title="roleModelTitle" @on-ok="ok('formItem')" @on-cancel="cancel" :loading="roleModelLoading"
               :mask-closable="false" :closable="false" ok-text="保存">
            <Form ref="formItem" :model="formItem" :rules="ruleItem" :label-width="80">
                <FormItem label="父节点" ref="menuName" v-show="showParent">
                    <Input maxlength="50" readonly="true" v-model="formItem.parentName" placeholder="输入菜单名称..."></Input>
                </FormItem>

                <FormItem label="菜单名称" prop="menuName" ref="menuName">
                    <Input maxlength="50" v-model="formItem.menuName" placeholder="输入菜单名称..."></Input>
                </FormItem>

                <FormItem label="路由地址" prop="menuUrl" ref="menuUrl">
                    <Input maxlength="50" v-model="formItem.menuUrl" placeholder="输入路由地址..."></Input>
                </FormItem>

                <FormItem label="资源编码" prop="permission" ref="permission">
                    <Input maxlength="50" v-model="formItem.permission" placeholder="输入权限值..."></Input>
                </FormItem>

                <FormItem label="图标" prop="icon" ref="icon">
                    <Input maxlength="50" v-model="formItem.icon" placeholder="输入图标..."></Input>
                </FormItem>

                <FormItem label="排序" prop="sort" ref="sort">
                    <Input type="number" v-model="formItem.sort" placeholder="输入排序..."></Input>
                </FormItem>

                <FormItem label="状态" prop="menuStatus">
                    <i-switch v-model="formItem.menuStatus" size="large" true-value="1" false-value="0">
                        <span slot="open">启用</span>
                        <span slot="close">禁用</span>
                    </i-switch>
                </FormItem>

                <FormItem label="备注" prop="remark">
                    <Input maxlength="1000" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           v-model="formItem.remark"
                           placeholder="输入备注..."></Input>
                </FormItem>
            </Form>
        </Modal>


        <Modal v-model="roleOpModel" :title="roleModelTitle" @on-ok="ok('formItemOp')" @on-cancel="cancel" :loading="roleModelLoading"
               :mask-closable="false" :closable="false" ok-text="保存">
            <Form ref="formItemOp" :model="formItemOp" :rules="ruleItem" :label-width="80">

                <FormItem label="资源名称" prop="menuName" ref="menuName">
                    <Input maxlength="50" v-model="formItemOp.menuName" placeholder="输入菜单名称..."></Input>
                </FormItem>

                <FormItem label="路由地址" prop="menuUrl" ref="menuUrl">
                    <Input maxlength="50" v-model="formItemOp.menuUrl" placeholder="输入路由地址..."></Input>
                </FormItem>

                <FormItem label="资源编码" prop="permission" ref="permission">
                    <Input maxlength="50" v-model="formItemOp.permission" placeholder="输入权限值..."></Input>
                </FormItem>

                <FormItem label="状态" prop="menuStatus">
                    <i-switch v-model="formItemOp.menuStatus" size="large" true-value="1" false-value="0">
                        <span slot="open">启用</span>
                        <span slot="close">禁用</span>
                    </i-switch>
                </FormItem>

                <FormItem label="备注" prop="remark">
                    <Input maxlength="1000" type="textarea" :autosize="{minRows: 2,maxRows: 5}"
                           v-model="formItemOp.remark"
                           placeholder="输入备注..."></Input>
                </FormItem>
            </Form>
        </Modal>

        <Spin fix size="large" fix v-if="spinShow">
            <Icon type="load-c" :size="18" class="demo-spin-icon-load"></Icon>
            <div>拼命加载中...</div>
        </Spin>
    </Row>
</template>
<script>

    import Util from '@/libs/util'

    var qs = require('qs');
    export default {
        components: {},
        data() {
            return {
                loading: false,
                spinShow: false,
                spinShowPanel: false,
                roleModel: false,
                roleOpModel: false,
                roleOpDisabled: true,
                roleModelLoading: true,
                roleModelTitle: '新增菜单',
                index: 0,
                total: 0,
                rows:[],
                show: 1,
                isOp:false,
                menusData: [],
                selectItem: null,
                showParent: false,
                formItem: {
                    menuId: '',
                    menuName: '',
                    menuUrl: '',
                    icon: '',
                    menusType: '1',
                    menuStatus: '1',
                    parentId: '',
                    parentName: '',
                    permission: '',
                    sort: '',
                    remark: '',
                    createTime: '',
                    systemSetId: ''
                },
                formItemOp: {
                    menuId: '',
                    menuName: '',
                    menuUrl: '',
                    icon: '',
                    menusType: '0',
                    menuStatus: '1',
                    parentId: '',
                    parentName: '',
                    permission: '',
                    sort: '',
                    remark: '',
                    createTime: '',
                    systemSetId: ''
                },
                ruleItem: {
                    menuName: [
                        {
                            required: true,
                            trigger: 'blur',
                            message: '菜单名称不能为空.'
                        },
                        {
                            max: 50,
                            message: '最大长度为50',
                            trigger: 'blur'
                        }
                    ],
                    menuUrl: [
                        {
                            required: true, trigger: 'blur', message: '角色编码不能为空.'
                        },
                        {
                            max: 50,
                            message: '最大长度为50',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
                            message: '以英文字母开头，只能包含英文字母、数字、下划线',
                            trigger: 'blur'
                        },
                        {
                            validator(rule, value, callback) {
                                if (!value || value == '') {
                                    callback(new Error('角色编码不能为空.'));
                                    return;
                                }
                                //没有修改则不验证
                                let menusUrl = sessionStorage.getItem('menu-url');
                                if (menusUrl == value) {
                                    callback();
                                    return;
                                }
                                Util.axios.post('/ms/menus/validateUrl', qs.stringify({menuUrl: value})).then(res => {
                                    if (!res.data.result)
                                        callback(new Error(res.data.msg));
                                    else
                                        callback();
                                });
                            }
                        }
                    ],
                    permission: [
                        {
                            required: true,
                            trigger: 'blur',
                            message: '角色编码不能为空.'
                        },
                        {
                            max: 50,
                            message: '最大长度为50',
                            trigger: 'blur'
                        },
                        {
                            type: 'string',
                            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
                            message: '以英文字母开头，只能包含英文字母、数字、下划线',
                            trigger: 'blur'
                        },
                        {
                            validator(rule, value, callback) {
                                if (!value || value == '') {
                                    callback(new Error('角色编码不能为空.'));
                                    return;
                                }
                                //没有修改则不验证
                                let permission = sessionStorage.getItem('menu-permission');
                                if (permission == value) {
                                    callback();
                                    return;
                                }
                                Util.axios.post('/ms/menus/validatePermission', qs.stringify({permission: value})).then(res => {
                                    if (!res.data.result)
                                        callback(new Error(res.data.msg));
                                    else
                                        callback();
                                });
                            }
                        }
                    ]
                },
                columns: [
                    {
                        title: '资源名称',
                        key: 'MENUNAME',
                        align: 'center',
                        editable: true
                    },
                    {
                        title: '资源编码',
                        key: 'PERMISSION',
                        align: 'center',
                        //fixed: 'left'
                    },
                    {
                        title: '当前状态',
                        key: 'MENUSTATUS',
                        align: 'center',
                        render: (h, params) => {
                            let roleStatus = params.row.MENUSTATUS;
                            return h('div', [
                                h('Tag', {
                                    props: {
                                        color: roleStatus == 1 ? "green" : "red"
                                    },
                                    on: {
                                        "on-change": (status) => {

                                        }
                                    }
                                }, roleStatus == 1 ? "启用" : "停用"),
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        render: (h, params) => {
                            let vm = this;
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'info',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            //显示资源窗口
                                            vm.roleOpModel = true;
                                            vm.requestSelect(params.row.MENUID, true);
                                        }
                                    }
                                }, '编辑'),
                                h('Poptip', {
                                    props: {
                                        confirm: true,
                                        title: '您确定要删除这条数据吗?',
                                        transfer: true
                                    },
                                    on: {
                                        'on-ok': () => {
                                            vm.requestDel(params.row.MENUID, true);
                                        }
                                    }
                                }, [
                                    h('Button', {
                                        style: {
                                            margin: '0 5px'
                                        },
                                        props: {
                                            type: 'error',
                                            placement: 'top',
                                            size: 'small'
                                        }
                                    }, '删除')
                                ])
                            ]);
                        }
                    }
                ],
            }
        },
        methods: {
            create() {
                let me = this;
                me.$refs['formItem'].resetFields();
                me.roleModel = true;
                if(me.selectItem)
                {
                    me.formItem.parentId = me.selectItem[0].id;
                    me.formItem.menuId = '';
                    me.showParent = true;
                    me.formItem.parentName= me.selectItem[0].title;
                }
            },
            /**
             * 添加菜单下的资源
             * */
            createOp() {
                let me = this;
                me.$refs['formItemOp'].resetFields();
                me.roleOpModel = true;
            },
            refresh() {
                this.showParent = false;
                this.roleOpDisabled = true;
                this.$refs['formItem'].resetFields();
                this.loadData();
            },
            loadData(item, callback) {
                let me = this;
                let pId = item ? item.id : '';
                Util.axios.post('/ms/menus/query', qs.stringify({pId: pId})).then(res => {
                    me.spinShow = false;
                    var data = res.data;
                    if (data.result) {
                        let ms = [];
                        data.data.forEach(menu => {
                            let children = menu.CHILDREN;
                            let m = {id: menu.MENUID, title: menu.MENUNAME};
                            if (children > 0)
                            {
                                m = {id: menu.MENUID, title: menu.MENUNAME, loading: false, children: []}
                            }
                            else{
                                m = {id: menu.MENUID, title: menu.MENUNAME, children: []}
                            }

                            ms.push(m);
                        });
                        if (callback) {
                            callback(ms);
                        }
                        else
                            me.menusData = ms;

                    }

                });
            },
            select(nodeKey) {
                let me = this;
                let node = me.$refs['menuTree'].getSelectedNodes();
                me.selectItem = nodeKey;
                me.showParent = false;
                //查询节点信息
                if (node.length > 0) {
                    me.spinShowPanel = true;
                    me.requestSelect(node[0].id);
                }
                else {
                    me.$refs['formItem'].resetFields();
                    me.roleOpDisabled = true;
                }
            },
            //根据Id 查询菜单详情
            requestSelect(id, state)
            {
                let me = this;
                Util.axios.post('/ms/menus/findById', qs.stringify({id: id})).then(res => {
                    me.spinShowPanel = false;
                    if (res.data.result) {
                        if(state)
                        {
                            me.formItemOp = res.data.data;
                            sessionStorage.setItem('menu-url', me.formItemOp.menuUrl);
                            sessionStorage.setItem('menu-permission', me.formItemOp.permission);
                        }else{
                            me.formItem = res.data.data;
                            sessionStorage.setItem('menu-url', me.formItem.menuUrl);
                            sessionStorage.setItem('menu-permission', me.formItem.permission);
                            me.roleOpDisabled = false;
                            me.formItemOp.parentId = me.formItem.menuId;
                            me.loadOp();
                        }
                    }
                    else {
                        me.$Message.error(res.data.msg);
                    }
                });
            },
            edit() {
                let me = this;
                me.roleModelTitle = '编辑菜单';
                let node = me.$refs['menuTree'].getSelectedNodes();
                if (node.length > 0) {
                    me.roleModel = true;
                }
                else
                {
                    me.$Message.error("请选择需要操作的数据节点");
                }

            },
            /**
             * 保存菜单
             * @param name
             */
            handleSubmit(name, form) {
                let me = this;
                this.roleModelLoading = false;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        me.spinShow = true;
                        Util.axios.post(form.menuId == '' ? '/ms/menus/save' : '/ms/menus/update', form).then(res => {
                            me.spinShow = false;
                            if (res.data.result) {

                                let iteration = function (array, base) {
                                    array.forEach(ref => {
                                        if (me.selectItem) {
                                            let id = ref.id;
                                            let selectId = me.selectItem[0].id;

                                            //修改
                                            if (id == selectId && form.menuId != '') {
                                                ref.title = form.menuName;
                                            }
                                            if (ref.children) {
                                                iteration(ref.children, ref);
                                            }
                                            //添加
                                            if (id == selectId && form.menuId == '') {
                                                ref.children.push({id: res.data.data, title: form.menuName, nodeKey: ref.nodeKey + 1});
                                            }
                                        }
                                    });
                                }
                                if(!me.isOp)
                                {
                                    iteration(me.menusData);
                                }
                                else{
                                    //关闭窗体
                                    me.roleOpModel = false;
                                    // 读取数据
                                    me.loadOp();
                                }
                            }
                            this.$Message.success(res.data.msg);
                            //关闭窗体
                            me.roleModel = false;
                        });
                    } else {
                        this.$nextTick(() => {
                            this.roleModelLoading = true;
                        });
                    }
                })

            },
            del() {
                let me = this;
                let node = me.$refs['menuTree'].getSelectedNodes();
                //查询节点信息
                if (node.length > 0) {

                    let nodeId = node[0].id;
                    me.$Modal.confirm({
                        title: '删除确定',
                        content: '是否继续删除?',
                        onOk: () => {
                            me.spinShow = true;
                            me.requestDel(nodeId);
                        },
                        onCancel: () => {
                            this.$Message.info('操作取消');
                        }
                    });
                }
                else {
                    me.$Message.error('请选择需要操作的数据节点');
                }
            },
            requestDel(nodeId, state)
            {
                let me = this;
                Util.axios.post('/ms/menus/del', qs.stringify({id: nodeId})).then(res => {
                    me.spinShow = false;
                    if (res.data.result) {

                        //删除资源的使用 刷新grid
                        if(state)
                        {
                            me.loadOp();
                        }
                        else
                        {
                            me.$refs['formItem'].resetFields();
                            this.$Modal.remove();
                            let iteration = function (array, base) {
                                array.forEach(ref => {
                                    if (me.selectItem) {
                                        let id = ref.id;
                                        if (id == nodeId) {
                                            let index = base.children.indexOf(ref);
                                            base.children.splice(index, 1);
                                            if (base.children == 0) {
                                                base.children = [];
                                            }
                                        }
                                        if (ref.children) {
                                            iteration(ref.children, ref);
                                        }
                                    }
                                });
                            }
                            iteration(me.menusData);
                        }
                    }
                    else
                        this.$Message.success(res.data.msg);
                });
            },
            ok(formItem) {
                let form = '';
                if('formItem' == formItem)
                {
                    form = this.formItem;
                }
                else
                {
                    form = this.formItemOp;
                    this.isOp = true;
                }
                this.handleSubmit(formItem, form)
            },
            cancel() {
                this.$Message.info('操作取消');
            },
            //查询菜单下的资源
            loadOp()
            {
                var me = this;
                me.loading = true;
                let page = {'size': 10, 'page': this.index, pId: me.selectItem[0].id};
                Util.axios.post('/ms/menus/queryOp', qs.stringify(page)).then(res => {
                    var data = res.data;
                    if (data.result) {
                        me.total = data.data.total;
                        me.rows = data.data.rows;
                    }
                    me.loading = false;
                });

            }
        },
        created() {
            this.loadData();
        }
    }
</script>
